'''
Created on May 16, 2010

iur - Universal Web Remote targetted for iphone
Copyright (C) 2010 forteresce@gmail.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

'''
import bottle
from bottle import route, run, send_file, view
import os
import player
from player import *
import sys
from dbus.exceptions import DBusException

ROOT = os.path.dirname(os.path.abspath(__file__))
eventHandler = None
collectionHandler = None

@route('/')
@view('index')
def index():
    return dict(players=player.PLAYERS)

@route('/player/:name', method='POST')
def player_select(name):
    global eventHandler, collectionHandler
    exec('eventHandler = %s%s()' % (name, player.EVENT_HANDLER), globals(), globals())
    exec('collectionHandler = %s%s()' % (name, player.COLLECTION_HANDLER), globals(), globals())
    return getCurrentSongJson()

@route('/stats/currentSong', method='POST')
def stats_currentSong():
    return getCurrentSongJson()

#===================== Player Event Handling ========================
@route('/playback/:command', method='POST')
def playback(command):
    try:
        exec('eventHandler.%s()' % command, globals(), globals())
    except DBusException as dbe:
        return getMessageJson(dbe.get_dbus_message())
    return getCurrentSongJson()

@route('/queue/add/:song', method='POST')
def addToQueue(song):
    try:
        eventHandler.addSongToQueue(song)
    except DBusException as dbe:
        return getMessageJson(dbe.get_dbus_message())
    return getCurrentSongJson()

@route('/volume/:command', method='POST')
def volume(command):
    exec('volume = eventHandler.volume%s()' % command, globals(), globals())
    return "{volume: '%s'}" % volume

#===================== Player Collection Handling ========================
@route('/albums/:startsWith', method='POST')
@view('albums')
def albums(startsWith):
    return dict(header=startsWith, albums=collectionHandler.getAlbums(startsWith))

@route('/songs/:albumId', method='POST')
def songs(albumId):
    songs = collectionHandler.getSongsInAlbum(albumId)
    return '{ songs: [' + ",".join([str(song.toJson()) for song in songs]) + ']}'

#===================== Static File Handling ========================        

@route('/js/:filename#.*#')
def static_js(filename):
    return send_file(filename, root=os.path.join(ROOT, './static/js/'))

@route('/jqt/:filename#.*#')
def static_jqt(filename):
    return send_file(filename, root=os.path.join(ROOT, './static/jqt/'))

@route('/images/:filename')
def static_images(filename):
    return send_file(filename, root=os.path.join(ROOT, './static/images/'))

@route('/css/:filename')
def static_css(filename):
    return send_file(filename, root=os.path.join(ROOT, './static/css/'))

@route('/:filename#.*\.manifest#')
def static(filename):
    send_file(filename, root=os.path.join(ROOT, './static/'), mimetype='text/cache-mainfest')
    
#==================Miscellaneous=================================================
def getCurrentSongJson():
    if not eventHandler:
        return getMessageJson('No player selected. Please select player on main screen.')
    song = eventHandler.getCurrentSong()
    
    if not song:
        return getMessageJson('Not currently playing')
    return '{song: ' + song.toJson() + '}'

def getMessageJson(message):
    return '{message: "%s"}' % message
    
#==================Simple To Std Error Log =============================
def log(str):
    sys.stderr.write('%s\n' % str)

def start():
    bottle.TEMPLATE_PATH = [os.path.join(ROOT, './views/')]
    run(host='0.0.0.0', port=7070)